<?php

namespace Core\Http\Client;

/**
 * 请求例子
 *
 * $body = new BagInterface();
 * $bag->set()->set();
 *
 * $response = HttpClient::send($bag);
 */
class HttpClient
{
    protected static $client;

    protected static function getClient()
    {
        if (!self::$client) {
            self::$client = new \GuzzleHttp\Client();
        }

        return self::$client;
    }

    protected static function getOptions(BagInterface $bag)
    {
        $method = $bag->method();

        $options['headers'] = $bag->header();

        if ($method === BagInterface::METHOD_GET) {
            $options['query'] = $bag->query();
        }

        if ($method === BagInterface::METHOD_POST) {
            $options['body'] = $bag->body();
        }

        return $options;
    }

    /**
     * 发送Bag结构数据, 返回一个HttpResponse结构体
     */
    public static function send(BagInterface $bag)
    {
        $client = self::getClient();

        // 设置参数
        $method     = $bag->method();
        $url        = $bag->url();
        $options    = self::getOptions($bag);

        // 发送请求
        $response = $client->request($method, $url, $options);

        // 返回数据
        return new HttpResponse($response);
    }
}
